package com.fyzk.activity.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseFragment;
import com.fyzk.activity.forum.FocusView;
import com.fyzk.activity.forum.ForumChildTopicBean;
import com.fyzk.activity.forum.ForumFocusBean;
import com.fyzk.activity.forum.ForumRecommendBean;
import com.fyzk.activity.forum.ForumUserInfoBean;
import com.fyzk.activity.forum.HeadView;
import com.fyzk.activity.forum.HotView;
import com.fyzk.activity.forum.ParallaxRecyclerAdapter;
import com.fyzk.activity.forum.TopicDetailActivity;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/4/26.
 *
 * 论坛
 */
public class ForumFragment extends BaseFragment {

    private TopTitleView topTitle;

    private View mainView;

    private RecyclerView recyclerView;
    private ParallaxRecyclerAdapter<ForumRecommendBean> adapter;

    private HeadView header;
    private FocusView focusView;
    private HotView hotView;

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private List<ForumRecommendBean> recommendInfos = new ArrayList<>();

    private boolean isLogin = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_forum, null);
        initView();
        return mainView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        net();
    }

    private void net() {
        isLogin = MySharedPreferences.getInstance().getLoginStatus();
        header.setLogin(isLogin);
        if (isLogin) {
            getUserInfo();
            getFocusList();
        }

        getChildTopicList(2);   // 获取热门话题list
//        getTopicList();
        getRecommendList();
    }

    private void initView() {
        topTitle = (TopTitleView) mainView.findViewById(R.id.forum_topTitle);
        topTitle.setCenterText("彩票圈子");
        topTitle.setOnTitleClickListener(this);
        recyclerView = (RecyclerView) mainView.findViewById(R.id.forum_recycler_view);
        mSwipeRefreshLayout = (SwipeRefreshLayout) mainView.findViewById(R.id.forum_swiperefreshlayout);

        header = new HeadView(getContext());
        focusView = new FocusView(getContext());
        hotView = new HotView(getContext());
        createAdapter(recyclerView);

        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 下拉刷新
                net();
            }
        });
    }

    /**
     *  获取用户信息（论坛）
     */
    private void getUserInfo() {
        try {
            JSONObject request_json = new JSONObject();

            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            request_json.put("data", new JSONObject());
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_USERINFO);

            params.setBodyContent("req="+URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_USERINFO, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取关注（论坛）
     */
    private void getFocusList() {
        try {
            JSONObject request_json = new JSONObject();

            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            request_json.put("data", new JSONObject());
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_FOCUS);

            params.setBodyContent("req="+URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_FOCUS, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取话子列表（论坛）
     */
    private void getChildTopicList(int parent_id) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("parent_id", parent_id);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_CHILDTOPICLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_CHILDTOPICLIST, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取推荐列表（论坛）
     */
    private void getRecommendList() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("page", 1);
            data.put("per_page", 10);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_RECOMMENDLIST);

            params.setBodyContent("req="+URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_RECOMMENDLIST, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
        switch (requestCode) {
            case CommandUtil.FORUM_USERINFO:
                ForumUserInfoBean userInfoBean = JSON.parseObject(resultBean.getData(), ForumUserInfoBean.class);
                header.setUserInfo(userInfoBean);
                break;
            case CommandUtil.FORUM_FOCUS:
                focusView.setInfo(JSON.parseArray(resultBean.getData(), ForumFocusBean.class));
                break;
            case CommandUtil.FORUM_CHILDTOPICLIST:
                ForumChildTopicBean childTopicBean = JSON.parseObject(resultBean.getData(), ForumChildTopicBean.class);
                hotView.setInfo(childTopicBean.getChild_topic());
                break;
            case CommandUtil.FORUM_RECOMMENDLIST:
                recommendInfos = JSON.parseArray(resultBean.getData(), ForumRecommendBean.class);
//                setContentViews();
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onFailure(int requestCode, String errorcode, String msg) {
        if (requestCode == CommandUtil.FORUM_USERINFO) {
            header.setLogin(false); // 获取用户信息失败，显示未登录
        } else {
            super.onFailure(requestCode, errorcode, msg);
        }
    }

    private void createAdapter(RecyclerView recyclerView) {

        adapter = new ParallaxRecyclerAdapter<ForumRecommendBean>(recommendInfos) {
            @Override
            public void onBindViewHolderImpl(RecyclerView.ViewHolder viewHolder,
                                             ParallaxRecyclerAdapter<ForumRecommendBean> adapter, int i) {
                ViewHolder holder = (ViewHolder) viewHolder;

                int position = i;
                if (i == 0) {
                    holder.ll_focus.setVisibility(View.VISIBLE);
                    holder.ll_hot.setVisibility(View.VISIBLE);
                    holder.ll2.setVisibility(View.GONE);
                } else {
                    final ForumRecommendBean recommendInfo = recommendInfos.get(position-1);
                    holder.ll_focus.setVisibility(View.GONE);
                    holder.ll_hot.setVisibility(View.GONE);
                    holder.ll2.setVisibility(View.VISIBLE);

                    if (i == 1) {
                        holder.itemHead_ll.setVisibility(View.VISIBLE);
                    } else {
                        holder.itemHead_ll.setVisibility(View.GONE);
                    }

                    holder.title_tv.setText(recommendInfo.getQuestion_content());
                    String topicName = "";
                    try {
                        topicName = recommendInfo.getTopics().get(0).getTopic_title();
                    } catch (Exception e) {
                        topicName = "话题";
                    }
                    holder.userName_tv.setText(recommendInfo.getUser_info().getUser_name() + " 发表于 " + topicName);
                    holder.ll2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getContext(), TopicDetailActivity.class);
                            intent.putExtra("id", recommendInfo.getQuestion_id());
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public RecyclerView.ViewHolder onCreateViewHolderImpl(ViewGroup viewGroup, final
            ParallaxRecyclerAdapter<ForumRecommendBean> adapter, int i) {
                return new ViewHolder(getActivity().getLayoutInflater().inflate(R.layout
                        .forum_list_item, viewGroup, false));
            }

            @Override
            public int getItemCountImpl(ParallaxRecyclerAdapter<ForumRecommendBean> adapter) {
                return recommendInfos.size()+1;
            }
        };

        adapter.setOnClickEvent(new ParallaxRecyclerAdapter.OnClickEvent() {
            @Override
            public void onClick(View v, int position) {
//                Toast.makeText(getContext(), "You clicked '" + position + "'", Toast
// .LENGTH_SHORT).show();
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter.setParallaxHeader(header, recyclerView);
        adapter.setData(recommendInfos);
        recyclerView.setAdapter(adapter);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout ll_focus;
        public LinearLayout ll_hot;
        public LinearLayout ll2;
        public LinearLayout itemHead_ll;
        public TextView title_tv;
        public TextView userName_tv;

        public ViewHolder(View itemView) {
            super(itemView);
            ll_focus = (LinearLayout) itemView.findViewById(R.id.forum_list_item_focus);
            ll_hot = (LinearLayout) itemView.findViewById(R.id.forum_list_item_hot);
            ll2 = (LinearLayout) itemView.findViewById(R.id.forum_list_item_ll2);
            itemHead_ll = (LinearLayout) itemView.findViewById(R.id.forum_list_item_head);
            title_tv = (TextView) itemView.findViewById(R.id.forum_list_item_title);
            userName_tv = (TextView) itemView.findViewById(R.id.forum_list_item_username);
            if (ll_focus.getChildCount() == 0) {
                try {

                    ll_focus.addView(focusView);
                } catch (Exception e) {

                }
            }
            if (ll_hot.getChildCount() == 0) {

                try {

                    ll_hot.addView(hotView);
                } catch (Exception e) {

                }
            }
        }
    }

    @Override
    public void onLeftClick() {
        getActivity().finish();
    }
}
